package com.itic.system.market.product.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.applications.sys.common.service.OutCommonService;
import com.itic.appbase.applications.websocket.SystemWebSocketHandler;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.exception.definition.ParameterErrorException;
import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.ValueHelper;
import com.itic.system.market.category.persistence.model.Category;
import com.itic.system.market.category.persistence.model.CategoryExample;
import com.itic.system.market.category.service.CategoryService;
import com.itic.system.market.product.persistence.model.Product;
import com.itic.system.market.product.persistence.model.ProductExample;
import com.itic.system.market.product.persistence.model.ProductExample.Criteria;
import com.itic.system.market.product.service.ProductService;
import com.itic.system.market.productitem.persistence.model.ProductItem;
import com.itic.system.market.productitem.persistence.model.ProductItemExample;
import com.itic.system.market.productitem.service.ProductItemService;


@Controller
@RequestMapping(value="/system/product")
public class ProductController
     extends BaseController {
    @Autowired
    private ProductService productService;

    @Autowired
    private ProductItemService productItemService;
    
    @Autowired
   	protected OutCommonService outCommonService;
    
    @Autowired
    protected CategoryService categoryService;
       
	@Bean
	public SystemWebSocketHandler systemWebSocketHandler() {
		return new SystemWebSocketHandler();
	}

	////////////////////////////////////////////////////// 常量区////////////////////////////////////////////////////////////////
	private static final String MODEL_NAME_CHINA = "视频管理";// 中文名
	private static final String MODEL_NAME＿ENGLISH = "product";// 英文名
	private static final String PAGE_COMMON_PATH = "edu/market/product/product";// 通用路径
	private static final String COMMON_URL = "/system/product/";// 通用路径
	private static final String CATEGORY = "T_DM_DEMO_PRODUCT_CATEGORY";// 代码表名称

	// 导出常量
	private static final String TEMP = "bzmc";// 备注名称
	private static final String DATALIST = "dataList";// 数据常量
	// 返回属性黑名单
	private static String[] ignoreProperties = new String[] { "createUser", "isEffective", "createTime", "updateTime",
			"orgCode" };

	////////////////////////////////////////////////////// 页面跳转区////////////////////////////////////////////////////////////

	/*
	 * 主页面
	 */
	@RequestMapping(value = "/init")
	public String init(Model model) {
		model.addAttribute("name_china", MODEL_NAME_CHINA);
		model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
		model.addAttribute("common_url", COMMON_URL);
		return PAGE_COMMON_PATH + "Main";
	}

	/*
	 * 添加页面
	 */
	@RequestMapping(value = "/initAdd")
	public String initAdd(Model model) {
		model.addAttribute("name_china", MODEL_NAME_CHINA);
		model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
		model.addAttribute("common_url", COMMON_URL);
		return PAGE_COMMON_PATH + "Add";
	}

	/*
	 * 编辑页面
	 */
	@RequestMapping(value = "/initEdit")
	public String initEdit(String id, Model model) {
		if (StringHelper.isNotBlank(id)) {
			Product temp = productService.get(id);
			ProductItemExample example = new ProductItemExample();
			com.itic.system.market.productitem.persistence.model.ProductItemExample.Criteria criteria = example.createCriteria();
			criteria.andIsEffectiveEqualTo(DBConst.TRUE);
			criteria.andProductIdEqualTo(id);
			List<ProductItem> items = productItemService.list(example);
			
			model.addAttribute("editData", iticJsonMapper.toJson(temp));
			model.addAttribute("items", iticJsonMapper.toJson(items));
			model.addAttribute("name_china", MODEL_NAME_CHINA);
			model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
			model.addAttribute("common_url", COMMON_URL);
		} else {
			throw new ParameterErrorException();
		}
		return PAGE_COMMON_PATH + "Edit";
	}

	/*
	 * 查看页面
	 */
	@RequestMapping(value = "/initView")
	public String initView(String id, Model model) {
		if (StringHelper.isNotBlank(id)) {

			Product temp = productService.get(id);
			temp.setCategoryCode(outCommonService.getNameByCode(CATEGORY, temp.getCategoryCode()));

			model.addAttribute("viewEdit", iticJsonMapper.toJson(temp));
			model.addAttribute("name_china", MODEL_NAME_CHINA);
			model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
			model.addAttribute("common_url", COMMON_URL);
		} else {
			throw new ParameterErrorException();
		}

		return PAGE_COMMON_PATH + "View";
	}

	/*
	 * 导入页面
	 */
	@RequestMapping(value = "/initImp")
	public String initImp(Model model) {
		model.addAttribute("name_china", MODEL_NAME_CHINA);
		model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
		model.addAttribute("common_url", COMMON_URL);
		return PAGE_COMMON_PATH + "Imp";
	}

	////////////////////////////////////////////////////// 业务代码区////////////////////////////////////////////////////////////

	/**
	 * 添加模板管理数据
	 * 
	 * @param android
	 * @return
	 */
	@RequestMapping(value = "/add")
	@ResponseBody
	public Map<String, String> add(Product temp,String items) {

		Map<String, String> resultMap = new HashMap<String, String>();
		String result = ResponseCode.SERVER_ERROR.getCode();
		//String unescapeXml = StringEscapeUtils.unescapeXml(temp.getStyleText());
		//temp.setStyleText(unescapeXml);
		result = productService.addProduct(temp,items);

		resultMap.put(IticConst.RESULT, result);
		return resultMap;
	}

	/**
	 * <p>
	 * Title:queryCondition
	 * </p>
	 * <p>
	 * Description:封装查询条件
	 * </p>
	 * 
	 * @param jzdw
	 * @param jzdwExample
	 * @return
	 */
	private ProductExample queryCondition(HttpServletRequest request, Product temp, String startTime, String stopTime) {

		// 参数处理
		ProductExample example = new ProductExample();
		// 按创建时间倒序
		example.setOrderByClause("UPDATE_TIME DESC");
		// 按排列号顺序
		//example.setOrderByClause("reorder asc");

		Criteria criteria = example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE);

		// 过滤组织机构
		// User user = findUserSession(request);
		// criteria.andOrgCodeEqualTo(user.getOrganizationCode());

		// 查询条件
		if (null != temp) {
			// 模糊查询
			if (StringHelper.isNotBlank(temp.getProductName())) {
				criteria.andProductNameLike("%" + temp.getProductName() + "%");
			}
			// 类别 查询
			if (StringHelper.isNotBlank(temp.getCategoryCode())) {
				criteria.andCategoryCodeEqualTo(temp.getCategoryCode());
			}
			if (StringHelper.isNotBlank(startTime)) {
				criteria.andCreateTimeGreaterThanOrEqualTo(
						DateHelper.getDateByStringDate(startTime + IticConst.START_TIME_SUFFIX));
			}
			if (StringHelper.isNotBlank(stopTime)) {
				criteria.andCreateTimeLessThanOrEqualTo(
						DateHelper.getDateByStringDate(stopTime + IticConst.END_TIME_SUFFIX));
			}
		}
		return example;
	}

	/**
	 * 
	 * @param goldType
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/list")
	@ResponseBody
	public Map<String, Object> list(Product temp, String startTime, String stopTime, HttpServletRequest request) {
		// 声明返回对象
		Map<String, Object> resultMap = new HashMap<String, Object>();

		ProductExample example = this.queryCondition(request, temp, startTime, stopTime);
		// 封装分页参数
		example = this.handlePageQuery(request, example);

		// 获取信息总条数
		int total = productService.count(example);

		// 获取数据
		List<Product> list = productService.list(example);

		// 结果集
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		if (list.size() > 0) {
			for (Product tmp : list) {
				Category category = categoryService.getByCode(tmp.getCategoryCode());
				if( null != category ){
					tmp.setCategoryCode(category.getCategoryName());
				}
			}
			// 过滤黑名单字段
			resultList = ValueHelper.tranList2MapList(list, ignoreProperties);
		}
       
		// 数据返回处理
		resultMap.put(IticConst.TOTAL_RECORDS, total);
		resultMap.put(IticConst.DISPLAY_RECORDS, total);
		resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
		resultMap.put(IticConst.DATA, resultList);
		return resultMap;

	}

	/**
	 * 编辑保存
	 * 
	 * @param Product
	 * @return
	 */
	@RequestMapping(value = "/edit")
	@ResponseBody
	public Map<String, String> edit(String items, Product temp) {

		Map<String, String> resultMap = new HashMap<String, String>();
		String result = ResponseCode.SERVER_ERROR.getCode();
		//String unescapeXml = StringEscapeUtils.unescapeXml(temp.getStyleText());
		//temp.setStyleText(unescapeXml);
		result = productService.editProduct(temp,items);

		resultMap.put(IticConst.RESULT, result);
		return resultMap;
	}

	/**
	 * 删除
	 * 
	 */
	@RequestMapping(value = "/del")
	@ResponseBody
	public Map<String, String> del(String id) {
		Map<String, String> resultMap = new HashMap<String, String>();
		String result = ResponseCode.SERVER_ERROR.getCode();

		// 删除一个
		if (StringHelper.isNotBlank(id)) {
			Product temp = new Product();
			temp.setId(id);
			result = productService.delete(temp);
		}

		resultMap.put(IticConst.RESULT, result);
		return resultMap;
	}
	
	/**
	 * 删除
	 * 
	 */
	@RequestMapping(value = "/top")
	@ResponseBody
	public Map<String, String> top(String id) {
		Map<String, String> resultMap = new HashMap<String, String>();
		String result = ResponseCode.SERVER_ERROR.getCode();

		// 删除一个
		if (StringHelper.isNotBlank(id)) {
			Product temp = new Product();
			temp.setId(id);
			temp.setUpdateTime(new Date());
			result = productService.edit(temp);
		}

		resultMap.put(IticConst.RESULT, result);
		return resultMap;
	}
	
	/**
	 * 获得类别
	 * @return
	 */
	@RequestMapping(value = "/getCategorys")
	@ResponseBody
	public List<Category> getCategorys(){
		CategoryExample example = new CategoryExample();
		com.itic.system.market.category.persistence.model.CategoryExample.Criteria criteria = example.createCriteria();
		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		List<Category> list = categoryService.list(example);
		return list;
	}

	/**
	 * exp
	 * 
	
	@RequestMapping(value = "/exp")
	@ResponseBody
	public void exp(HttpServletRequest request, HttpServletResponse response, Product temp, String startTime,
			String stopTime) {
		try {
			// 参数处理
			ProductExample example = new ProductExample();
			example = this.queryCondition(request, temp, startTime, stopTime);
			// 获取数据
			List<Product> list = productService.list(example);
			// 导出
			Map<String, Object> exportMap = new HashMap<String, Object>();
			exportMap.put(TEMP, MODEL_NAME＿ENGLISH);
			exportMap.put(DATALIST, list);
			ExportExcel exportExcel = new ExportExcelWithProduct();
			exportExcel.exportExcel(exportMap, request, response);

		} catch (Exception e) {
			throw new RuntimeException("[ProductController | exp 模板示例导出异常]");
		}
	} */

	/**
	 * exp
	 * 
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/imp")
	@ResponseBody
	public Map<String, String> imp(HttpServletRequest request, String fileId) {
		Map<String, String> resultMap = new HashMap<String, String>();
		String result = ResponseCode.SERVER_ERROR.getCode();
		try {
			// 获取Excel解析数据
			Map<String, Object> excelDataMap = new HashMap<String, Object>();
			String filePath = outCommonService.getFilePath(fileId);
			if (StringHelper.isNotBlank(filePath)) {
				excelDataMap = ImportExcelUtil.readValue(new File(FileHelper.getRootDir(), filePath),
						MODEL_NAME＿ENGLISH);
			}
			// 获取验证错误List集合
			List<String> errorInfoList = (List<String>) excelDataMap.get("error");
			// 获取对象组成的List集合
			List<Product> dataList = (List<Product>) excelDataMap.get("data");
			if (errorInfoList != null && errorInfoList.size() > 0) {
				// 处理错误信息，返回前台
				result = "error";
				resultMap.put(IticConst.DATA, "ERROR");
				request.getSession().setAttribute("ExcelImpError", errorInfoList);
			} else if (dataList != null && dataList.size() > 0) {
				// 处理excel数据
				result = productService.imp(request, dataList);
			}

		} catch (Exception e) {
			throw new RuntimeException("[ProductController | imp 模板示例导入异常]");
		}
		resultMap.put(IticConst.RESULT, result);
		return resultMap;
	} */
}